//
//  PxReaderView.h
//  Express
//
//  Created by 泰然财富 on 15/7/28.
//  Copyright (c) 2015年 泰然财富. All rights reserved.
//

#import "PxHistoryView.h"
#import "LLSmallUtil.h"
#import "PxGlobal.h"
#import "PxWidgetCreater.h"

@implementation PxHistoryView {
    CGPoint lastPoint;
    BOOL isHidden;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        lastPoint = CGPointMake(0, 0);
        isHidden = YES;
    }
    return self;
}

-(void)addView:(UIView *)view
{
    CGRect frame = self.bounds;
    CGFloat lastX = lastPoint.x + view.width + 8;
    CGFloat lastY = lastPoint.y;
    if (lastX > frame.size.width) {
        lastY = view.height + 15;
        lastX = 0;
        view.left = lastX;
        view.top = lastY;
    } else {
        if (lastPoint.x == 0) {
            lastX = lastPoint.x + view.width;
            view.left = 0;
        } else
            view.left = lastPoint.x + 8;
        view.top = lastY;
    }
    [self addSubview:view];
    lastPoint = CGPointMake(lastX, lastY);
    
    self.height = lastY + view.height + 30;//30为清除按钮高度+15
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self initSubviews];
    [self initLastBtn];
}

-(void)initLastBtn
{
    CGRect frame = self.bounds;
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];
    [btn setHidden:isHidden];
    btn.height = 15;
    btn.top = frame.origin.y + frame.size.height - btn.height;
    btn.titleLabel.font = [UIFont systemFontOfSize:12];
    [btn setTitle:@"清除搜索记录"];
    [btn setTitleColor:[UIColor colorWithHTMLStr:@"2f86e9"] forState:UIControlStateNormal];
    [btn setSelector:@selector(clearAll) withTarget:self];
    [self addSubview:btn];
}

-(void)initSubviews
{
    NSString *values = [PxGlobal getData:HISTORY];
    if (values.length == 0) {
        isHidden = YES;
        return;
    }
    isHidden = NO;
    NSArray *arrs = [values componentsSeparatedByString:@","];
    for (NSString *tmp in arrs) {
        UILabel *label1 = [PxWidgetCreater getUILabelView:tmp andTarget:self];
        [self addView:label1];
    }
}

-(void)clearAll
{
    LLDLog(@"clearAll");
    [PxGlobal removeData:HISTORY];
    [self resetAll];
}

- (void)resetAll
{
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
}

-(void)gotoQuery:(UITapGestureRecognizer *)gestureRecognizer
{
    UILabel *label = (UILabel *)gestureRecognizer.view;
    LLDLog(@"text:%@", label.text);
    if (_delegate) {
        [_delegate labelClick:label.text];
    }
}
@end